<?php

class USR {
  var $conn;

  function __construct( $servername, $username, $password, $dbname){
    $this->conn = new mysqli($servername, $username, $password, $dbname);
    if ($this->conn->connect_error){
      $this->conn = -1;
      return;
    }
    $this->conn->set_charset("utf8");
  }

  function __destruct(){
    $this->conn->close();
  }

  function get($name){
    $stmtusr = $this->conn->prepare('SELECT uid, name, pwd FROM bkmk_usr WHERE name = ?');

    $stmtusr->bind_param('s', $name);
    $stmtusr->execute();
    $stmtusr->store_result();
    $stmtusr->bind_result($uid, $uname, $upwd);
    if($stmtusr->fetch()){

      $data = array();
      $data['uid']  = $uid;
      $data['name'] = $uname;
      $data['pwd']  = $upwd;

    }else{

      $data = false;

    }

    $stmtusr->close();

    return $data;
  }

  function getByID($uid){
    $stmtusr = $this->conn->prepare('SELECT uid, name, pwd FROM bkmk_usr WHERE uid = ?');

    $stmtusr->bind_param('i', $uid);
    $stmtusr->execute();
    $stmtusr->store_result();
    $stmtusr->bind_result($rid, $rname, $rpwd);

    if($stmtusr->fetch()){

      $data = array();
      $data['uid']  = $rid;
      $data['name'] = $rname;
      $data['pwd']  = $rpwd;

    }else{

      $data = false;

    }

    $stmtusr->close();

    return $data;
  }

  function add($username, $password){
    $stmtusr = $this->conn->prepare('INSERT INTO bkmk_usr ( name, pwd ) VALUES ( ?, ? )');

    $stmtusr->bind_param('ss', $username, $password);
    $stmtusr->execute();

    $stmtusr->close();

    return true;
  }

  function del($uid){
    $stmtusr = $this->conn->prepare('DELETE FROM bkmk_usr WHERE uid = ?');

    $stmtusr->bind_param('i', $uid);
    $stmtusr->execute();

    $stmtusr->close();

    return true;
  }

  function alt($uid, $password){
    $stmtusr = $this->conn->prepare('UPDATE bkmk_usr SET pwd = ? WHERE uid = ?');

    $stmtusr->bind_param('si', $password, $uid);
    $stmtusr->execute();

    $stmtusr->close();

    return true;
  }
}

